package util

import (
	"time"

	"github.com/gin-gonic/gin"
)

var ipIntervalLimitPool = make(map[string]int64)
var ipIntervalMaxLength = 100

// 如果被限流了，返回 false，可以通行，返回true
func LimitIpInterval(c *gin.Context, intervalSeconds int64) bool {
	ip := c.Request.Header.Get("X-Forward-For")
	lastTp, ok := ipIntervalLimitPool[ip]
	currentTp := time.Now().Unix()
	ipIntervalLimitPool[ip] = currentTp

	if !ok {
		ipIntervalLimitPool[ip] = time.Now().Unix()
		return true
	}
	if currentTp - lastTp <= intervalSeconds {
		return false	
	}
	// 及时清理
	if len(ipIntervalLimitPool) > ipIntervalMaxLength {
		for k := range ipIntervalLimitPool {
			delete(ipIntervalLimitPool, k)
		}
	}

	return true
}